﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using InfFront.UICore;
using InfFront.InfoViews.Base;

namespace InfFront.InfoViews.WPF
{
    /// <summary>
    /// Interaction logic for ErrorDialog.xaml
    /// </summary>
    public partial class ErrorDialog : Window
    {
        private double tbDetailsHeight = 0;

        public ErrorDialog(InfoViewSource src, Exception ex)
        {
            DataContext = src;

            InitializeComponent();

            FillTexts(ex);
        }

        private void FillTexts(Exception ex)
        {
            tbBoldMessage.Text = ex.Message;

            var sb = new StringBuilder(tbDetails.Text);
            sb.AppendLine();
            FillWithInnerException(sb, ex);
            tbDetails.Text = sb.ToString();
        }

        private void FillWithInnerException(StringBuilder sb, Exception ex)
        {
            sb.AppendFormat("{0}: {1}", ex.GetType().Name, ex.Message);
            sb.AppendLine();
            if (!string.IsNullOrEmpty(ex.Source))
            {
                sb.AppendFormat("Source: {0}", ex.Source);
                sb.AppendLine();
            }
            sb.AppendLine("Trace:");
            sb.Append(ex.StackTrace);
            sb.AppendLine();
            if (ex.InnerException != null)
            {
                sb.AppendLine();
                sb.Append("Inner ");
                FillWithInnerException(sb, ex.InnerException);
            }
        }

        private void ResizeToContent()
        {
            if (!cbShowDetails.IsChecked.HasValue || !cbShowDetails.IsChecked.Value)
                tbDetails.Height = 0;
            else
                tbDetails.Height = tbDetailsHeight;
        }

        private void cbShowDetails_Checked(object sender, RoutedEventArgs e)
        {
            ResizeToContent();
            e.Handled = true;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void ThisWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            tbDetailsHeight = tbDetails.Height;
            tbDetails.Height = 0;
            this.SizeChanged -= ThisWindow_SizeChanged;
            e.Handled = true;
        }
    }
}
